package controllers;

import com.google.gson.JsonElement;
import common.FBUtil;

import models.User;
import play.Play;
import play.cache.Cache;
import play.mvc.Controller;

public class FBController extends Controller {
	protected static User getUser() {
    return (User)request.args.get("user.obj");
	}
	
	protected static String getOAuthToken() {
		User user = getUser();
		return Cache.get("app.OAUTH_" + user.getFacebookID(), String.class);
	}
	
	protected static void setFbIdandName() {
			
			User currentUser = getUser();
		    
			if (currentUser == null) {
		        notFound("INVALID_USER"); // we should not be here!
		    }
		      
		    String oauthToken = getOAuthToken();
		    
		    if (currentUser == null) {
		        notFound("INVALID_AUTH_TOKEN"); // we should not be here!
		    }
		    	
		    	
		    	
		    String facebookName = null;
		    String userImage = null;
		    String userImageBig = null;
		    	
		    JsonElement je = FBUtil.getInstance().executeGraphRequest("/me", oauthToken);
		    
		    if ((je != null) && (je.isJsonObject()) && (je.getAsJsonObject().has("name"))) {
		    	facebookName = je.getAsJsonObject().get("name").getAsString();
		    	userImage = "https://graph.facebook.com/" + je.getAsJsonObject().get("id").getAsString() + "/picture";
		    	userImageBig = "https://graph.facebook.com/" + je.getAsJsonObject().get("id").getAsString() + "/picture?type=large";
		    }
		    	
		    String facebookApplicationID = Play.configuration.getProperty("fb.app.id"); 
		    
		    currentUser.setName(facebookName);
		    currentUser.setProfilPicture(userImage);
		    currentUser.setProfilPictureBig(userImageBig);
		    
		    currentUser.save();
		    	
		    renderArgs.put("facebookName", facebookName);
		    renderArgs.put("facebookApplicationID", facebookApplicationID);
		    renderArgs.put("userImage", userImage);
		    renderArgs.put("userImageBig", userImageBig);
		    renderArgs.put("userId", currentUser.getId());
		}
}
